package model;

import java.awt.Point;
import java.util.LinkedList;

import javax.swing.event.EventListenerList;

public class DefaultModel extends LinkedList<Courbe> {
	Courbe courbeCourante;
	private EventListenerList listenerList;
	private PointControl currentPoint;
	private boolean displayTengente;
	public final static int sideLength = 10;

	public DefaultModel() {
		super();
		listenerList = new EventListenerList();
		courbeCourante = null;
	}

	public void add(Point destination) {
		System.out.println("Ajout d'un point");
		if (courbeCourante == null) {
			courbeCourante = new Courbe();
			this.add(courbeCourante);
		}
		this.currentPoint  = new PointControl(destination, courbeCourante);
		courbeCourante.add(currentPoint);
		this.fireModelChanged();
	}

	public void finishCourbe() {
		courbeCourante = null;

	}

	public boolean isOverPoint(Point a) {
		return find(a) != null;
	}

	private PointControl find(Point a) {
		for (Courbe c : this) {
			for (PointControl p : c) {
				if (a.getX() - sideLength < p.getX()
						&& a.getX() + sideLength > p.getX()
						&& a.getY() - sideLength < p.getY()
						&& a.getY() + sideLength > p.getY())
					return p;
			}
		}
		return null;
	}

	public void remove(PointControl removedPoint) {
		PointControl remove = this.find(removedPoint);
		remove.getCourbes().remove(remove);
		this.fireModelChanged();
	}

	public void movePoint(Point origine, Point destination) {
		this.find(origine).setLocation(destination);
		this.fireModelChanged();
	}

	/**
	 * Écouteur de validitée de cette case
	 */

	public ModelListener[] getModelListeners() {
		return this.listenerList.getListeners(ModelListener.class);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see model.InterfaceModel#addModelListener(model.modelListener)
	 */
	public void addModelListener(final ModelListener listener) {
		this.listenerList.add(ModelListener.class, listener);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see model.InterfaceModel#removeModelListener(model.modelListener)
	 */
	public void removeModelListener(final ModelListener listener) {
		this.listenerList.remove(ModelListener.class, listener);
	}

	protected void fireModelChanged() {

		for (final ModelListener listener : this.getModelListeners()) {
			listener.onePointChange();
		}
	}

	public void select(Point p) {
		this.currentPoint = this.find(p);
		fireModelChanged();
	}

	public void setTangente(Point p) {
		currentPoint.setTangente(p);
		fireModelChanged();
	}

	public void moveCurrentPoint(Point p) {
		currentPoint.setLocation(p);
		fireModelChanged();
	}

	public boolean isOverTangente(Point p) {
		// TODO Auto-generated method stub
		return false;
	}

	public void displayTengente(boolean b) {
		this.displayTengente = b;
		fireModelChanged();
	}
	
	public boolean isCurrentTangentePoint(PointControl pc){
		return displayTengente&&currentPoint == pc;
	}
}